from .common import *

class ViewGeneratorPage5(wx.adv.WizardPage):
    '''个性化创建视图【第五页】'''
    def __init__(self, parent, title='第五步：选择写入路径', out_data = None):
        WizardPageSimple.__init__(self, parent)
        self.next = self.prev = None
        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.SetSizer(self.sizer)
        if out_data is not None:
            self.out_data = out_data
            if VIEWS_WIZARD_CONTEXT not in self.out_data:
                self.out_data[VIEWS_WIZARD_CONTEXT] = {}
            self.context = self.out_data[VIEWS_WIZARD_CONTEXT]
            self.context['5'] = {}
            self.context = self.context['5']
        else:
            raise Exception('没有上下文，无法开启向导页面')

        self._init_UI(title)
        self._init_listener()

    def _init_UI(self, title):
        '''初始化界面布局'''
        '''
            设置当前页标题
        '''
        title = wx.StaticText(self, -1, title)
        title.SetFont(wx.Font(16, wx.FONTFAMILY_SWISS, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD))
        self.sizer.Add(title, 0, wx.ALIGN_LEFT|wx.ALL, 3)
        self.sizer.Add(wx.StaticLine(self, -1), 0, wx.EXPAND|wx.ALL, 5) # 水平分割线

        '''
            所有的其他控件全部放在滚动面板中
        '''
        self.scollPanel = scrolledpanel.ScrolledPanel(self, -1, size=SIZE) # 定义滚动面板
        self.scollPanel.SetupScrolling() # 开启滚动
        self.scollPanelSizer = wx.BoxSizer(wx.VERTICAL)
        self.scollPanel.SetSizer(self.scollPanelSizer)
        self.sizer.Add(self.scollPanel, 1, wx.EXPAND | wx.ALL, 2) # 加入主容器

        self._init_scollpanel()

    def _init_scollpanel(self):
        '''初始化滚动窗口'''
        '''
            视图写入路径设置
        '''
        self.staticBoxViewPath = wx.StaticBox(self.scollPanel, -1, '视图写入路径设置')
        self.staticBoxViewPathSizer = wx.StaticBoxSizer(self.staticBoxViewPath, wx.VERTICAL)
        self.scollPanelSizer.Add(self.staticBoxViewPathSizer, 0, wx.EXPAND | wx.ALL, 6)
        self.staticBoxViewPath.SetForegroundColour(wx.BLUE)

        self.radioBoxViewPathChoice = wx.RadioBox(self.scollPanel, -1, '', choices=['默认视图路径', '指定视图文件路径'])
        self.staticBoxViewPathSizer.Add(self.radioBoxViewPathChoice, 0, wx.ALL, 5)

        self._init_scollpanel_view_ctrls()

        '''
            路由路径设置窗口
        '''
        self.staticBoxUrlPath = wx.StaticBox(self.scollPanel, -1, '路由名称和写入路径设置')
        self.staticBoxUrlPathSizer = wx.StaticBoxSizer(self.staticBoxUrlPath, wx.VERTICAL)
        self.scollPanelSizer.Add(self.staticBoxUrlPathSizer, 0, wx.EXPAND | wx.ALL, 6)
        self.staticBoxUrlPath.SetForegroundColour(wx.BLUE)

        self.radioBoxUrlPathChoice = wx.RadioBox(self.scollPanel, -1, '', choices=['默认路由路径', '指定路由文件路径'])
        self.staticBoxUrlPathSizer.Add(self.radioBoxUrlPathChoice, 0, wx.ALL, 5)

        ### 选择性路由显示控件
        self._init_scollpanel_url_ctrls()

    def _init_scollpanel_view_ctrls(self):
        """选择性视图显示控件"""
        self.flexGridSizer = wx.FlexGridSizer(cols=3, hgap=5, vgap=2)
        self.staticBoxViewPathSizer.Add(self.flexGridSizer, 1, wx.EXPAND | wx.ALL, 5)
        self.flexGridSizer.AddGrowableCol(1) 

        # 控件
        self.staticTextViewApp = wx.StaticText(self.scollPanel, -1, '归属应用程序')
        self.choiceViewApp = wx.Choice(self.scollPanel, -1, choices=[' ', *djangotools.SCONFIGS.app_names()])
        self.labelViewMustChoice = wx.StaticText(self.scollPanel, -1, label='必选')
        self.labelViewMustChoice.SetForegroundColour(wx.RED)

        self.staticTextViewFile = wx.StaticText(self.scollPanel, -1, '归属视图文件')
        self.choiceViewFile = wx.Choice(self.scollPanel, -1, choices=[*env.get_file_alias('views')])
        self.choiceViewFile.SetSelection(0)
        self.labelViewMustChoice2 = wx.StaticText(self.scollPanel, -1, label='必选')
        self.labelViewMustChoice2.SetForegroundColour(wx.RED)

        self.checkBoxViewAutoSearch = wx.CheckBox(self.scollPanel, -1, label = '深层路径查找(默认根级路径查找)')

        self.inputViewFilePath = wx.TextCtrl(self.scollPanel, -1, value='')
        self.btnViewFilePath = buttons.GenButton(self.scollPanel, -1, label='选择视图写入路径')
        self.labelViewMustChoice3 = wx.StaticText(self.scollPanel, -1, label='必选')
        self.labelViewMustChoice3.SetForegroundColour(wx.RED)
        self.inputViewFilePath.Show(False)
        self.btnViewFilePath.Show(False)
        self.labelViewMustChoice3.Show(False)
        
        # 注入布局
        self.flexGridSizer.Add(self.staticTextViewApp, 0, wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL)
        self.flexGridSizer.Add(self.choiceViewApp, 0, wx.EXPAND)
        self.flexGridSizer.Add(self.labelViewMustChoice, 0, wx.EXPAND)

        self.flexGridSizer.Add(self.staticTextViewFile, 0, wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL)
        self.flexGridSizer.Add(self.choiceViewFile, 0, wx.EXPAND)
        self.flexGridSizer.Add(self.labelViewMustChoice2, 0, wx.EXPAND)

        self.flexGridSizer.Add((5,5), 0, wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL)
        self.flexGridSizer.Add(self.checkBoxViewAutoSearch, 0, wx.EXPAND)
        self.flexGridSizer.Add((5,5), 0, wx.EXPAND)

    def _init_scollpanel_url_ctrls(self):
        """路由路径设置窗口"""
        self.flexGridSizerUrl = wx.FlexGridSizer(cols=3, hgap=5, vgap=2)
        self.staticBoxUrlPathSizer.Add(self.flexGridSizerUrl, 1, wx.EXPAND | wx.ALL, 5)
        self.flexGridSizerUrl.AddGrowableCol(1) 

        # 控件
        self.staticTextUrlApp = wx.StaticText(self.scollPanel, -1, '归属应用程序')
        self.choiceUrlApp = wx.Choice(self.scollPanel, -1, choices=[' ', *djangotools.SCONFIGS.app_names()])
        self.labelUrlMustChoice = wx.StaticText(self.scollPanel, -1, label='必选')
        self.labelUrlMustChoice.SetForegroundColour(wx.RED)

        self.staticTextUrlFile = wx.StaticText(self.scollPanel, -1, '归属路由文件')
        self.choiceUrlFile = wx.Choice(self.scollPanel, -1, choices=[*env.get_file_alias('urls')])
        self.choiceUrlFile.SetSelection(0)
        self.labelUrlMustChoice2 = wx.StaticText(self.scollPanel, -1, label='必选')
        self.labelUrlMustChoice2.SetForegroundColour(wx.RED)

        self.checkBoxUrlAutoSearch = wx.CheckBox(self.scollPanel, -1, label = '深层路径查找(默认根级路径查找)')

        self.inputUrlFilePath = wx.TextCtrl(self.scollPanel, -1, value='')
        self.btnUrlFilePath = buttons.GenButton(self.scollPanel, -1, label='选择路由写入路径')
        self.labelUrlMustChoice3 = wx.StaticText(self.scollPanel, -1, label='必选')
        self.labelUrlMustChoice3.SetForegroundColour(wx.RED)
        self.inputUrlFilePath.Show(False)
        self.btnUrlFilePath.Show(False)
        self.labelUrlMustChoice3.Show(False)
        
        # 注入布局
        self.flexGridSizerUrl.Add(self.staticTextUrlApp, 0, wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL)
        self.flexGridSizerUrl.Add(self.choiceUrlApp, 0, wx.EXPAND)
        self.flexGridSizerUrl.Add(self.labelUrlMustChoice, 0, wx.EXPAND)

        self.flexGridSizerUrl.Add(self.staticTextUrlFile, 0, wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL)
        self.flexGridSizerUrl.Add(self.choiceUrlFile, 0, wx.EXPAND)
        self.flexGridSizerUrl.Add(self.labelUrlMustChoice2, 0, wx.EXPAND)

        self.flexGridSizerUrl.Add((5,5), 0, wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL)
        self.flexGridSizerUrl.Add(self.checkBoxUrlAutoSearch, 0, wx.EXPAND)
        self.flexGridSizerUrl.Add((5,5), 0, wx.EXPAND)

    def _init_listener(self):
        """注册监听"""
        '''
            向导页面事件监听
        '''
        self.Bind(wx.adv.EVT_WIZARD_PAGE_CHANGING, self.onWizPageChanging)
        self.Bind(wx.adv.EVT_WIZARD_CANCEL, self.onWizCancel)

        '''
            视图写入路径事件监听
        '''
        self.Bind(wx.EVT_CHOICE, self.onChoiceViewApp, self.choiceViewApp)
        self.Bind(wx.EVT_RADIOBOX, self.onRadioBoxViewPathChoice, self.radioBoxViewPathChoice)
        self.Bind(wx.EVT_BUTTON, self.onBtnViewFilePath, self.btnViewFilePath)

        '''
            路由写入路径事件监听
        '''
        self.Bind(wx.EVT_CHOICE, self.onChoiceUrlApp, self.choiceUrlApp)
        self.Bind(wx.EVT_RADIOBOX, self.onRadioBoxUrlPathChoice, self.radioBoxUrlPathChoice)
        self.Bind(wx.EVT_BUTTON, self.onBtnUrlFilePath, self.btnUrlFilePath)

    def onChoiceViewApp(self, evt):
        """选择归属应用程序"""
        self.choiceUrlApp.SetSelection(evt.GetSelection())

    def onChoiceUrlApp(self, evt):
        """选择归属应用程序"""
        self.choiceViewApp.SetSelection(evt.GetSelection())

    def onBtnViewFilePath(self, evt):
        """选择视图写入路径"""
        files = RichMsgDialog.showSelectFilesDialog(self, "", info="请选择写入的视图文件")
        if len(files) > 0:
            # 当多选时仅取第一个文件路径
            self.inputViewFilePath.SetValue(files[0])
        else:
            RichMsgDialog.showOkMsgDialog(self, "您未选择任何视图文件！", "错误")

    def onBtnUrlFilePath(self, evt):
        """选择视图写入路径"""
        files = RichMsgDialog.showSelectFilesDialog(self, "", info="请选择写入的路由文件")
        if len(files) > 0:
            # 当多选时仅取第一个文件路径
            self.inputUrlFilePath.SetValue(files[0])
        else:
            RichMsgDialog.showOkMsgDialog(self, "您未选择任何路由文件！", "错误")

    def onWizCancel(self, evt):
        """界面取消时触发"""
        if not RichMsgDialog.showYesNoMsgDialog(self, '【取消】/【关闭】将导致已填的数据全部被丢弃！', "警告"):
            evt.Veto()

    def onWizPageChanging(self, evt):
        """向导页切换时触发"""
        # evt.Veto()
        app_name = self.choiceUrlApp.GetString(self.choiceUrlApp.GetSelection()).strip()
        view_file_name = self.choiceViewFile.GetString(self.choiceViewFile.GetSelection()).strip()
        url_file_name = self.choiceUrlFile.GetString(self.choiceUrlFile.GetSelection()).strip()

        pathView, pathUrl = '', ''
        if 0 == self.radioBoxViewPathChoice.GetSelection():
            if not app_name or not view_file_name:
                RichMsgDialog.showOkMsgDialog(self, "归属应用程序、归属视图文件 必选", "错误")
                evt.Veto()
                return
            pathView = djangotools.get_path_by_appname_filename(app_name, view_file_name, self.checkBoxViewAutoSearch.IsChecked())
        else:
            pathView = self.inputViewFilePath.GetValue().strip()

        if 0 == self.radioBoxUrlPathChoice.GetSelection():
            if not app_name or not url_file_name:
                RichMsgDialog.showOkMsgDialog(self, "归属应用程序，归属路由文件 必选", "错误")
                evt.Veto()
                return
            pathUrl = djangotools.get_path_by_appname_filename(app_name, url_file_name, self.checkBoxUrlAutoSearch.IsChecked())
        else:
            pathUrl = self.inputUrlFilePath.GetValue().strip()

        self.context['view_path'] = pathView
        self.context['url_path'] = pathUrl

        if not self.context['view_path']:
            RichMsgDialog.showOkMsgDialog(self, "视图路径为空（若选择【默认视图路径】，请尝试勾选【深层路径查找】）", "错误")
            evt.Veto()
            return

        if not self.context['url_path']:
            RichMsgDialog.showOkMsgDialog(self, "路由路径为空（若选择【默认路由路径】，请尝试勾选【深层路径查找】）", "错误")
            evt.Veto()
            return

        if not os.path.exists(self.context['view_path']):
            RichMsgDialog.showOkMsgDialog(self, "请选择合法的视图路径", "错误")
            evt.Veto()
            return

        if not os.path.exists(self.context['url_path']):
            RichMsgDialog.showOkMsgDialog(self, "请选择合法的路由路径", "错误")
            evt.Veto()
            return

    def _unshow_view_ctrls(self):
        """隐藏视图相关控件"""
        self.staticTextViewApp.Show(False)
        self.choiceViewApp.Show(False)
        self.labelViewMustChoice.Show(False)

        self.staticTextViewFile.Show(False)
        self.choiceViewFile.Show(False)
        self.labelViewMustChoice2.Show(False)

        self.checkBoxViewAutoSearch.Show(False)

        self.inputViewFilePath.Show(False)
        self.btnViewFilePath.Show(False)
        self.labelViewMustChoice3.Show(False)

    def _unshow_url_ctrls(self):
        """隐藏路由相关控件"""
        self.staticTextUrlApp.Show(False)
        self.choiceUrlApp.Show(False)
        self.labelUrlMustChoice.Show(False)

        self.staticTextUrlFile.Show(False)
        self.choiceUrlFile.Show(False)
        self.labelUrlMustChoice2.Show(False)

        self.checkBoxUrlAutoSearch.Show(False)

        self.inputUrlFilePath.Show(False)
        self.btnUrlFilePath.Show(False)
        self.labelUrlMustChoice3.Show(False)

    def onRadioBoxViewPathChoice(self, evt):
        '''视图写入路径设置 生成方式选择'''
        select = evt.GetSelection()
        self.flexGridSizer.Clear()
        self._unshow_view_ctrls()# 隐藏所有控件
        if 0 == select:
            self.staticTextViewApp.Show(True)
            self.choiceViewApp.Show(True)
            self.labelViewMustChoice.Show(True)

            self.staticTextViewFile.Show(True)
            self.choiceViewFile.Show(True)
            self.labelViewMustChoice2.Show(True)

            self.checkBoxViewAutoSearch.Show(True)

            self.flexGridSizer.Add(self.staticTextViewApp, 0, wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL)
            self.flexGridSizer.Add(self.choiceViewApp, 0, wx.EXPAND)
            self.flexGridSizer.Add(self.labelViewMustChoice, 0, wx.EXPAND)

            self.flexGridSizer.Add(self.staticTextViewFile, 0, wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL)
            self.flexGridSizer.Add(self.choiceViewFile, 0, wx.EXPAND)
            self.flexGridSizer.Add(self.labelViewMustChoice2, 0, wx.EXPAND)

            self.flexGridSizer.Add((5,5), 0, wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL)
            self.flexGridSizer.Add(self.checkBoxViewAutoSearch, 0, wx.EXPAND)
            self.flexGridSizer.Add((5,5), 0, wx.EXPAND)
        else:
            self.flexGridSizer.Add(self.btnViewFilePath, 0, wx.EXPAND|wx.ALIGN_CENTER_VERTICAL)
            self.flexGridSizer.Add(self.inputViewFilePath, 0, wx.EXPAND)
            self.flexGridSizer.Add(self.labelViewMustChoice3, 0, wx.EXPAND)

            self.inputViewFilePath.Show(True)
            self.btnViewFilePath.Show(True)
            self.labelViewMustChoice3.Show(True)

        self.scollPanel.Layout()

    def onRadioBoxUrlPathChoice(self, evt):
        '''路由写入路径设置 生成方式选择'''
        select = evt.GetSelection()
        self.flexGridSizerUrl.Clear()
        self._unshow_url_ctrls()# 隐藏所有控件
        if 0 == select:
            self.staticTextUrlApp.Show(True)
            self.choiceUrlApp.Show(True)
            self.labelUrlMustChoice.Show(True)

            self.staticTextUrlFile.Show(True)
            self.choiceUrlFile.Show(True)
            self.labelUrlMustChoice2.Show(True)

            self.checkBoxUrlAutoSearch.Show(True)

            self.flexGridSizerUrl.Add(self.staticTextUrlApp, 0, wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL)
            self.flexGridSizerUrl.Add(self.choiceUrlApp, 0, wx.EXPAND)
            self.flexGridSizerUrl.Add(self.labelUrlMustChoice, 0, wx.EXPAND)

            self.flexGridSizerUrl.Add(self.staticTextUrlFile, 0, wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL)
            self.flexGridSizerUrl.Add(self.choiceUrlFile, 0, wx.EXPAND)
            self.flexGridSizerUrl.Add(self.labelUrlMustChoice2, 0, wx.EXPAND)

            self.flexGridSizerUrl.Add((5,5), 0, wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL)
            self.flexGridSizerUrl.Add(self.checkBoxUrlAutoSearch, 0, wx.EXPAND)
            self.flexGridSizerUrl.Add((5,5), 0, wx.EXPAND)
        else:
            self.flexGridSizerUrl.Add(self.btnUrlFilePath, 0, wx.EXPAND|wx.ALIGN_CENTER_VERTICAL)
            self.flexGridSizerUrl.Add(self.inputUrlFilePath, 0, wx.EXPAND)
            self.flexGridSizerUrl.Add(self.labelUrlMustChoice3, 0, wx.EXPAND)

            self.inputUrlFilePath.Show(True)
            self.btnUrlFilePath.Show(True)
            self.labelUrlMustChoice3.Show(True)

        self.scollPanel.Layout()

    def SetNext(self, next):
        '''设置后一页'''
        self.next = next

    def SetPrev(self, prev):
        '''设置前一页'''
        self.prev = prev

    def GetNext(self):
        '''获取下一页/下一指定页'''
        return self.next

    def GetPrev(self):
        '''获取上一页/上一指定页'''
        return self.prev